﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web.Script.Serialization;
using Natural.Attributes;
using Newtonsoft.Json;

namespace Natural.Providers
{
    

   
    [Impl(Type = ImplType.Provider, Name = "Serializer", Strategy = "Json", Version = 0, Priority = 0)]
    public class JsonSerializer : ISerializer
    {
        private JavaScriptSerializer javaScriptSerializer;
        public JsonSerializer()
        {
            javaScriptSerializer = new JavaScriptSerializer();
        }
        public T Deserialize<T>(string input)
        {
            return (T)Deserialize(input, typeof(T));
        }
        public object Deserialize(string input, Type targetType)
        {
            return javaScriptSerializer.Deserialize(input, targetType);
        }
        public object DeserializeObject(string input)
        {
            return javaScriptSerializer.DeserializeObject(input);
        }
        public string Serialize(object obj)
        {
            return javaScriptSerializer.Serialize(obj);
        }
        private class NullPropertiesConverter : JavaScriptConverter
        {
            public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
            {
                throw new NotImplementedException();
            }

            public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
            {
                var jsonExample = new Dictionary<string, object>();
                foreach (var prop in obj.GetType().GetProperties())
                {
                    //check if decorated with ScriptIgnore attribute
                    bool ignoreProp = prop.IsDefined(typeof(ScriptIgnoreAttribute), true);

                    var value = prop.GetValue(obj, BindingFlags.Public, null, null, null);
                    if (value != null && !ignoreProp)
                        jsonExample.Add(prop.Name, value);
                }

                return jsonExample;
            }

            public override IEnumerable<Type> SupportedTypes
            {
                get { return GetType().Assembly.GetTypes(); }
            }
        }
    }


}
